from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from contextlib import contextmanager
import os

# 获取项目根目录
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 数据库文件路径
DATABASE_URL = f"sqlite:///{os.path.join(PROJECT_ROOT, 'transactions.db')}"

# 创建数据库引擎
engine = create_engine(
    DATABASE_URL, 
    connect_args={"check_same_thread": False},
    echo=True  # 启用SQL语句日志
)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建基本模型类
Base = declarative_base()

@contextmanager
def get_db_context():
    """获取数据库会话的上下文管理器"""
    db = SessionLocal()
    try:
        yield db
        db.commit()  # 如果没有异常，提交事务
    except Exception:
        db.rollback()  # 如果有异常，回滚事务
        raise
    finally:
        db.close()  # 总是关闭会话

def get_db():
    """获取数据库会话的依赖项（用于FastAPI的Depends）"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close() 